// 占卜流程管理类 - 实现完整的占卜流程和叙事重构原理
import { aiService } from '../services/aiService.js';

export class DivinationProcess {
  constructor() {
    this.currentStep = 0;
    this.userQuestion = '';
    this.selectedSpread = null;
    this.drawnCards = [];
    this.interpretation = '';
    this.aiAnalysis = null;
    this.aiSummary = null;
    this.emotionAnalysis = null;
    this.processSteps = [
      '问题聚焦',
      '阵型选择',
      '洗牌准备',
      '抽牌过程',
      '结果解读',
      'AI增强解读',
      '叙事重构'
    ];
  }

  // 开始占卜流程
  startDivination() {
    this.currentStep = 0;
    this.userQuestion = '';
    this.selectedSpread = null;
    this.drawnCards = [];
    this.interpretation = '';
    return this.getCurrentStepInfo();
  }

  // 获取当前步骤信息
  getCurrentStepInfo() {
    const step = this.processSteps[this.currentStep];
    const stepDescriptions = {
      '问题聚焦': '请仔细思考你想要占卜的问题，将其具体化、清晰化。好的问题能带来更准确的指引。',
      '阵型选择': '选择适合你问题的占卜阵型。不同的阵型适合不同类型的问题。',
      '洗牌准备': '通过洗牌来准备牌组，这个过程象征着清理心灵，为占卜做准备。',
      '抽牌过程': '根据选择的阵型抽取相应数量的塔罗牌。',
      '结果解读': '解读每张牌的含义，理解它们如何回答你的问题。',
      'AI增强解读': 'AI智能分析你的问题和牌组，提供个性化解读和情感分析。',
      '叙事重构': '将塔罗牌的指引整合成完整的故事，帮助你重新理解现状和找到方向。'
    };

    return {
      step: step,
      description: stepDescriptions[step],
      stepNumber: this.currentStep + 1,
      totalSteps: this.processSteps.length
    };
  }

  // 设置用户问题
  setUserQuestion(question) {
    this.userQuestion = question;
    return this.validateQuestion(question);
  }

  // 验证问题质量
  validateQuestion(question) {
    const validation = {
      isValid: true,
      suggestions: [],
      score: 0
    };

    if (!question || question.trim().length < 5) {
      validation.isValid = false;
      validation.suggestions.push('问题太短，请详细描述你的困扰或疑问');
      validation.score = 0;
    } else if (question.length > 200) {
      validation.isValid = false;
      validation.suggestions.push('问题太长，请简洁明了地表达');
      validation.score = 0;
    } else {
      // 评估问题质量
      let score = 0;
      
      // 检查是否包含具体情境
      if (question.includes('什么') || question.includes('如何') || question.includes('为什么')) {
        score += 2;
      }
      
      // 检查是否包含情感词汇
      if (question.includes('感觉') || question.includes('担心') || question.includes('希望')) {
        score += 1;
      }
      
      // 检查是否包含时间概念
      if (question.includes('现在') || question.includes('未来') || question.includes('过去')) {
        score += 1;
      }
      
      // 检查是否过于绝对
      if (question.includes('永远') || question.includes('绝对') || question.includes('一定')) {
        score -= 1;
        validation.suggestions.push('避免使用绝对化的词汇，保持开放心态');
      }
      
      validation.score = Math.max(0, Math.min(5, score));
      
      if (score < 2) {
        validation.suggestions.push('尝试让问题更具体，包含更多细节');
      }
    }

    return validation;
  }

  // 选择占卜阵型
  selectSpread(spread) {
    this.selectedSpread = spread;
    return {
      spreadName: spread.getName(),
      positions: spread.getPositions(),
      cardCount: spread.positions.length
    };
  }

  // 进入下一步
  nextStep() {
    if (this.currentStep < this.processSteps.length - 1) {
      this.currentStep++;
      return this.getCurrentStepInfo();
    }
    return null; // 已经是最后一步
  }

  // 返回上一步
  previousStep() {
    if (this.currentStep > 0) {
      this.currentStep--;
      return this.getCurrentStepInfo();
    }
    return null; // 已经是第一步
  }

  // 设置抽牌结果
  setDrawnCards(cards) {
    this.drawnCards = cards;
    return this.generateInterpretation();
  }

  // 生成基础解读
  generateInterpretation() {
    if (!this.drawnCards || this.drawnCards.length === 0) {
      return '请先完成抽牌过程';
    }

    let interpretation = `\n🔮 塔罗牌解读结果\n`;
    interpretation += `📝 你的问题：${this.userQuestion}\n`;
    interpretation += `🎴 使用阵型：${this.selectedSpread ? this.selectedSpread.getName() : '未知阵型'}\n\n`;

    this.drawnCards.forEach((card, index) => {
      const position = this.selectedSpread && this.selectedSpread.positions ? 
        this.selectedSpread.positions[index] : `位置${index + 1}`;
      const cardName = card.name;
      const isReversed = card.isReversed;
      const meaning = isReversed ? card.reversed.meaning : card.upright.meaning;
      const description = isReversed ? card.reversed.description : card.upright.description;
      const keywords = card.keywords.join('、');

      interpretation += `📍 ${position}：${cardName}\n`;
      interpretation += `   ${isReversed ? '🔄 逆位' : '✅ 正位'}\n`;
      interpretation += `   💡 关键词：${keywords}\n`;
      interpretation += `   📖 含义：${meaning}\n`;
      interpretation += `   💭 详细描述：${description}\n\n`;
    });

    this.interpretation = interpretation;
    return interpretation;
  }

  // 生成叙事重构
  generateNarrativeReconstruction() {
    if (!this.interpretation) {
      return '请先完成基础解读';
    }

    let narrative = `\n🌟 叙事重构 - 重新理解你的故事\n\n`;
    
    // 分析牌组主题
    const themes = this.analyzeCardThemes();
    narrative += `🎯 整体主题：${themes.mainTheme}\n`;
    narrative += `🔍 核心信息：${themes.coreMessage}\n\n`;
    
    // 生成故事线
    const storyLine = this.generateStoryLine();
    narrative += `📚 你的故事：\n${storyLine}\n\n`;
    
    // 提供行动建议
    const actions = this.generateActionSuggestions();
    narrative += `💪 行动建议：\n${actions}\n\n`;
    
    // 展望未来
    const future = this.generateFutureOutlook();
    narrative += `🔮 未来展望：\n${future}\n\n`;
    
    // 整合建议
    narrative += `✨ 整合建议：\n`;
    narrative += `塔罗牌为你揭示了一个关于${themes.mainTheme}的故事。`;
    narrative += `通过${storyLine}，你可以${actions}。`;
    narrative += `记住，塔罗牌是镜子，反映的是你内心的智慧和直觉。`;
    narrative += `相信自己的判断，勇敢地面对${themes.mainTheme}的挑战和机遇。`;

    return narrative;
  }

  // 分析牌组主题
  analyzeCardThemes() {
    const themes = {
      mainTheme: '',
      coreMessage: '',
      elementBalance: { 火: 0, 水: 0, 风: 0, 土: 0 },
      orientationBalance: { upright: 0, reversed: 0 }
    };

    // 统计元素和正逆位
    this.drawnCards.forEach(card => {
      if (card.element) {
        themes.elementBalance[card.element]++;
      }
      if (card.isReversed) {
        themes.orientationBalance.reversed++;
      } else {
        themes.orientationBalance.upright++;
      }
    });

    // 确定主要主题
    const dominantElement = Object.entries(themes.elementBalance)
      .sort(([,a], [,b]) => b - a)[0][0];
    
    const elementThemes = {
      '火': '行动与激情',
      '水': '情感与直觉',
      '风': '思维与沟通',
      '土': '物质与稳定'
    };

    themes.mainTheme = elementThemes[dominantElement] || '个人成长';
    
    // 生成核心信息
    if (themes.orientationBalance.reversed > themes.orientationBalance.upright) {
      themes.coreMessage = '当前面临挑战，需要重新审视和调整';
    } else if (themes.orientationBalance.upright > themes.orientationBalance.reversed) {
      themes.coreMessage = '能量积极，适合采取行动和推进计划';
    } else {
      themes.coreMessage = '平衡状态，需要整合不同方面的能量';
    }

    return themes;
  }

  // 生成故事线
  generateStoryLine() {
    if (!this.selectedSpread || !this.drawnCards) {
      return '无法生成故事线';
    }

    let story = '';
    const positions = this.selectedSpread.positions || [];
    
    this.drawnCards.forEach((card, index) => {
      const position = positions[index] || `位置${index + 1}`;
      const cardName = card.name;
      const isReversed = card.isReversed;
      const meaning = isReversed ? card.reversed.meaning : card.upright.meaning;
      
      story += `在${position}方面，${cardName}告诉你${meaning}。`;
      
      if (index < this.drawnCards.length - 1) {
        story += ' ';
      }
    });

    return story;
  }

  // 生成行动建议
  generateActionSuggestions() {
    const suggestions = [];
    
    this.drawnCards.forEach(card => {
      if (card.isReversed) {
        // 逆位牌通常需要调整和改变
        suggestions.push(`重新审视${card.name}所代表的方面，寻找新的方法`);
      } else {
        // 正位牌通常鼓励行动
        suggestions.push(`发挥${card.name}的能量，积极行动`);
      }
    });

    // 根据牌组整体情况调整建议
    const reversedCount = this.drawnCards.filter(card => card.isReversed).length;
    if (reversedCount > this.drawnCards.length / 2) {
      suggestions.push('当前需要更多反思和调整，不要急于行动');
    } else if (reversedCount < this.drawnCards.length / 3) {
      suggestions.push('能量积极，适合推进计划，采取行动');
    } else {
      suggestions.push('保持平衡，既有行动也有反思');
    }

    return suggestions.join('；') + '。';
  }

  // 生成未来展望
  generateFutureOutlook() {
    const outlooks = [];
    
    this.drawnCards.forEach(card => {
      const cardName = card.name;
      const isReversed = card.isReversed;
      
      if (isReversed) {
        outlooks.push(`${cardName}的逆位提醒你注意${card.reversed.meaning}，但这也意味着你有机会改变现状`);
      } else {
        outlooks.push(`${cardName}的正位预示着${card.upright.meaning}，继续保持这种积极能量`);
      }
    });

    // 根据整体能量给出综合展望
    const positiveCards = this.drawnCards.filter(card => !card.isReversed).length;
    const totalCards = this.drawnCards.length;
    
    if (positiveCards > totalCards * 0.7) {
      outlooks.push('整体能量积极向上，未来充满希望和可能性');
    } else if (positiveCards < totalCards * 0.3) {
      outlooks.push('当前面临挑战，但每一次挑战都是成长的机会，保持信心');
    } else {
      outlooks.push('未来充满变化和机遇，保持开放和灵活的心态');
    }

    return outlooks.join('。') + '。';
  }

  // 获取完整的占卜结果
  getCompleteResult() {
    return {
      question: this.userQuestion,
      spread: this.selectedSpread ? this.selectedSpread.getName() : '',
      cards: this.drawnCards,
      interpretation: this.interpretation,
      narrative: this.generateNarrativeReconstruction(),
      timestamp: new Date().toLocaleString('zh-CN')
    };
  }

  // 生成AI增强解读
  async generateAIEnhancedInterpretation() {
    if (!this.drawnCards || this.drawnCards.length === 0) {
      return '请先完成抽牌过程';
    }

    try {
      // 生成AI个性化解读
      this.aiAnalysis = await aiService.generatePersonalizedInterpretation(
        this.userQuestion,
        this.drawnCards,
        this.selectedSpread
      );

      // 生成AI总结
      this.aiSummary = await aiService.generateAISummary(
        this.userQuestion,
        this.drawnCards,
        this.interpretation,
        this.generateNarrativeReconstruction()
      );

      // 生成情感分析
      this.emotionAnalysis = await aiService.analyzeEmotionAndAdvice(
        this.userQuestion,
        this.drawnCards
      );

      return this.formatAIEnhancedInterpretation();
    } catch (error) {
      console.error('AI增强解读生成失败:', error);
      return 'AI增强解读生成失败，请稍后重试';
    }
  }

  // 格式化AI增强解读
  formatAIEnhancedInterpretation() {
    let aiInterpretation = `\n🤖 AI智能增强解读\n`;
    aiInterpretation += `📝 问题分析：${this.userQuestion}\n\n`;

    // 添加AI问题分析
    if (this.aiAnalysis && this.aiAnalysis.data) {
      const analysis = this.aiAnalysis.data;
      
      if (analysis.questionInsights && analysis.questionInsights.length > 0) {
        aiInterpretation += `🔍 问题洞察：\n`;
        analysis.questionInsights.forEach(insight => {
          aiInterpretation += `   • ${insight}\n`;
        });
        aiInterpretation += `\n`;
      }

      if (analysis.cardConnections && analysis.cardConnections.length > 0) {
        aiInterpretation += `🔗 牌与问题连接：\n`;
        analysis.cardConnections.forEach(connection => {
          aiInterpretation += `   • ${connection.card}：${connection.connection}\n`;
        });
        aiInterpretation += `\n`;
      }

      if (analysis.personalizedMeanings && analysis.personalizedMeanings.length > 0) {
        aiInterpretation += `💫 个性化含义：\n`;
        analysis.personalizedMeanings.forEach(meaning => {
          aiInterpretation += `   • ${meaning.card}：${meaning.personalMeaning}\n`;
          aiInterpretation += `     相关性：${meaning.relevance}\n`;
          aiInterpretation += `     个人建议：${meaning.personalAdvice}\n`;
        });
        aiInterpretation += `\n`;
      }

      if (analysis.actionGuidance) {
        aiInterpretation += `🎯 行动指导：\n`;
        if (analysis.actionGuidance.immediate) {
          aiInterpretation += `   立即行动：\n`;
          analysis.actionGuidance.immediate.forEach(action => {
            aiInterpretation += `     • ${action}\n`;
          });
        }
        if (analysis.actionGuidance.shortTerm) {
          aiInterpretation += `   短期行动：\n`;
          analysis.actionGuidance.shortTerm.forEach(action => {
            aiInterpretation += `     • ${action}\n`;
          });
        }
        if (analysis.actionGuidance.mindset) {
          aiInterpretation += `   心态指导：${analysis.actionGuidance.mindset}\n`;
        }
        aiInterpretation += `\n`;
      }
    }

    // 添加AI总结
    if (this.aiSummary && this.aiSummary.data) {
      const summary = this.aiSummary.data;
      
      if (summary.keyInsights && summary.keyInsights.length > 0) {
        aiInterpretation += `💡 关键洞察：\n`;
        summary.keyInsights.forEach(insight => {
          aiInterpretation += `   • ${insight}\n`;
        });
        aiInterpretation += `\n`;
      }

      if (summary.practicalSteps && summary.practicalSteps.length > 0) {
        aiInterpretation += `📋 实用步骤：\n`;
        summary.practicalSteps.forEach(step => {
          aiInterpretation += `   ${step.step}. ${step.action}\n`;
          aiInterpretation += `      时间：${step.timeframe} | 优先级：${step.priority}\n`;
        });
        aiInterpretation += `\n`;
      }

      if (summary.futureOutlook) {
        aiInterpretation += `🔮 未来展望：${summary.futureOutlook}\n\n`;
      }

      if (summary.wisdomQuotes && summary.wisdomQuotes.length > 0) {
        aiInterpretation += `✨ 智慧语录：\n`;
        summary.wisdomQuotes.forEach(quote => {
          aiInterpretation += `   • ${quote.card}：${quote.quote}\n`;
        });
        aiInterpretation += `\n`;
      }
    }

    // 添加情感分析
    if (this.emotionAnalysis && this.emotionAnalysis.data) {
      const emotion = this.emotionAnalysis.data;
      
      if (emotion.currentEmotions) {
        aiInterpretation += `😊 情感分析：\n`;
        if (emotion.currentEmotions.questionEmotions) {
          const emotions = emotion.currentEmotions.questionEmotions;
          const emotionNames = {
            fear: '担忧',
            hope: '希望',
            confusion: '困惑',
            anger: '愤怒',
            sadness: '悲伤',
            joy: '快乐',
            love: '爱'
          };
          
          Object.entries(emotions).forEach(([key, count]) => {
            aiInterpretation += `   • ${emotionNames[key] || key}：${count}次提及\n`;
          });
        }
        aiInterpretation += `   整体情绪：${this.getEmotionDescription(emotion.currentEmotions.overallMood)}\n\n`;
      }

      if (emotion.emotionalPatterns && emotion.emotionalPatterns.length > 0) {
        aiInterpretation += `🔄 情感模式：\n`;
        emotion.emotionalPatterns.forEach(pattern => {
          aiInterpretation += `   • ${pattern}\n`;
        });
        aiInterpretation += `\n`;
      }

      if (emotion.healingSuggestions && emotion.healingSuggestions.length > 0) {
        aiInterpretation += `💝 治愈建议：\n`;
        emotion.healingSuggestions.forEach(suggestion => {
          aiInterpretation += `   • ${suggestion}\n`;
        });
        aiInterpretation += `\n`;
      }

      if (emotion.growthOpportunities && emotion.growthOpportunities.length > 0) {
        aiInterpretation += `🌱 成长机会：\n`;
        emotion.growthOpportunities.forEach(opportunity => {
          aiInterpretation += `   • ${opportunity}\n`;
        });
        aiInterpretation += `\n`;
      }
    }

    return aiInterpretation;
  }

  // 获取情绪描述
  getEmotionDescription(mood) {
    const descriptions = {
      positive: '积极向上，充满希望',
      negative: '面临挑战，需要支持',
      balanced: '平衡稳定，需要整合'
    };
    return descriptions[mood] || '未知状态';
  }

  // 获取AI分析结果
  getAIAnalysis() {
    return {
      questionAnalysis: this.aiAnalysis,
      summary: this.aiSummary,
      emotionAnalysis: this.emotionAnalysis
    };
  }

  // 重置占卜流程
  reset() {
    this.currentStep = 0;
    this.userQuestion = '';
    this.selectedSpread = null;
    this.drawnCards = [];
    this.interpretation = '';
    this.aiAnalysis = null;
    this.aiSummary = null;
    this.emotionAnalysis = null;
  }
} 